<?php

class Model {

    public function getMonitorsList($page,$armin,$armax,$marka,$kepatlo,$leiras,$conn,$page_size=10) {

        $armin = $conn->real_escape_string($armin);
        $armax = $conn->real_escape_string($armax);
        $marka = $conn->real_escape_string($marka);
        $kepatlo = $conn->real_escape_string($kepatlo);
        $leiras = $conn->real_escape_string($leiras);
        $page = $conn->real_escape_string($page);

        /* query for a page */

        $query_base = "SELECT `monitor_id`
				   , MAX( IF(attrib_name='kepatlo',attrib_value,'') ) as kepatlo
				   , MAX( IF(attrib_name='felbontas',attrib_value,'') ) as felbontas
				   , MAX( IF(attrib_name='marka',attrib_value,'') ) as marka
				   , MAX( IF(attrib_name='ar',attrib_value,'') ) as ar
				   , MAX( IF(attrib_name='akciosar',attrib_value,'') ) as akciosar
				   , MAX( IF(attrib_name='nev',attrib_value,'') ) as nev
				   , MAX( IF(attrib_name='leiras',attrib_value,'') ) as leiras
				FROM monitors GROUP BY monitor_id";

        $havingClause = " HAVING 1 = 1 ";

        if($armin != '') {
            $havingClause .= " AND CAST(SUBSTRING_INDEX(ar,' ',1) AS UNSIGNED) >=$armin";
        }
        if($armax != '') {
            $havingClause .= " AND CAST(SUBSTRING_INDEX(ar,' ',1) AS UNSIGNED) <=$armax";
        }
        if($marka != '') {
            $havingClause .= " AND marka='$marka' ";
        }
        if($kepatlo != '') {
            $havingClause .= " AND kepatlo='$kepatlo\"' ";
        }
        if($leiras != '') {
            $havingClause .= " AND leiras LIKE '%$leiras%' ";
        }

        $limit = " LIMIT ". ($page-1)*$page_size .",$page_size";
        $query = $query_base.$havingClause.$limit;

        $result = $conn->query($query);

        $list = array();
        while($row = mysqli_fetch_assoc($result)) {
            $list[] = $row;
        }

        /* query for the number of pages */

        $query2 = $query_base.$havingClause;
        $result2 = $conn->query($query2);

        $list2 = array();
        while($row = mysqli_fetch_assoc($result2)) {
            $list2[] = $row;
        }

        $pages = ceil(count($list2)/$page_size);

        return array($list,$pages);
    }

}
